package com.kaishengit.dao;

import com.kaishengit.entity.Prod;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class ProdDao {

	DBHelp<Prod> db=new DBHelp<Prod>();
	public List<Prod> getAllProds(){
		String sql="select id,prodname,price from t_prod";
		return db.executeQueryForList(sql, new ProdRowMapper());
	}
	public Prod findProdById(String id){
		String sql="select id,prodname,price from t_prod where id=?";
		return db.executeQueryForObject(sql, new ProdRowMapper(), id);
		
	}

	public List<Prod> findByOrderId(String orderid){
		String sql="SELECT id,prodname,price FROM t_prod WHERE id IN (SELECT prodid FROM t_orderitem WHERE orderid=?)";
		return db.executeQueryForList(sql, new ProdRowMapper(), orderid);
	}
	
	public boolean update(Prod prod){
		String sql="update t_prod set prodname=?,price=? where id=?";
		return db.executeSQL(sql, prod.getProdname(),prod.getPrice(),prod.getId());
	}
	
	public boolean save(Prod prod){
		String sql="insert into t_prod (prodname,price) values(?,?)";
		return db.executeSQL(sql, prod.getProdname(),prod.getPrice());
	}
	
	public boolean delete(String id){
		String sql="delete from t_prod where id=?";
		return db.executeSQL(sql, id);
	}
	
	private class ProdRowMapper implements RowMapper<Prod>{

		@Override
		public Prod mapRow(ResultSet rs) throws SQLException {
			Prod prod=new Prod();
			prod.setId(rs.getInt("id"));
			prod.setProdname(rs.getString("prodname"));
			prod.setPrice(rs.getFloat("price"));
			return prod;
		}
	}
}
